package com.shopx.auth.service.impl;

import com.shopx.auth.bean.SysOrg;
import com.shopx.auth.bean.SysUserCp;
import com.shopx.auth.dao.db1.SysOrgDao;
import com.shopx.auth.dao.db1.SysUserOrgDao;
import com.shopx.auth.model.SysOrgModel;
import com.shopx.auth.model.SysUserCpModel;
import com.shopx.auth.model.SysUserModel;
import com.shopx.auth.model.SysUserOrgModel;
import com.shopx.auth.service.ISysOrgService;
import com.shopx.auth.service.ISysUserCpService;
import com.shopx.auth.service.ISysUserService;
import com.shopx.base.exception.OriginException;
import com.shopx.base.service.base.BaseService;
import com.shopx.core.common.CommonConstant;
import com.shopx.core.utils.StringUtil;
import com.shopx.dal.redis.RedisCacheService;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lituo
 * @version 1.0
 * @descript TODO
 * @date 2022/1/11 13:42
 */
public class BaseAuthService extends BaseService {
  @Resource
  private ISysUserService sysUserService;

  @Resource
  private RedisCacheService redisCacheService;

  @Resource
  private ISysOrgService sysOrgService;
  /**
   * @return com.shopx.auth.model.SysUserModel
   * @descript 获取当前登录用户信息
   * @author lituo
   * @date 2022/1/11 13:43
   */
  protected SysUserModel getLoginUserInfo() {
    //走缓存
    String cacheKey = CommonConstant.CacheKey.USER_CACHE+super.getLoginUserId();
    Object userInfo = redisCacheService.get(cacheKey);
    if(userInfo==null){
      String userId = super.getLoginUserId();
      SysUserModel sysUser = new SysUserModel();
      sysUser.setUserId(userId);
      SysUserModel model = sysUserService.selectByPrimaryKey(sysUser);
      redisCacheService.set(cacheKey,model,7200);
      return  model;
    }else{
      return  (SysUserModel)userInfo;
    }
  }

  /**
   * 获取当前登录用户orgId，list方式返回
   * @return
   */
  protected List<SysUserOrgModel> getUserOrgIList() {
    return  this.getLoginUserInfo().getOrgList();
  }

  /**
   * 获取当前登录用户orgId，字符串形式返回
   * @auth lituo
   * @date 24.5.23 1:47 下午
   * @return java.lang.String
   **/
  protected String getUserOrgId() {
    return  this.getLoginUserInfo().getOrgIds();
  }

  /**
   * 获取用户部门列表,数组形式返回
   *
   * @return java.lang.String[]
   * @author lituo
   * @date 7:47 PM 2022/2/8
   * @param  userId
   */
  protected String[] queryUserOrgList(String userId) {
    return this.getUserOrgId().split(",");
  }

  /**
   * @return java.lang.String
   * @descript 获取当前登录用户角色信息
   * @author lituo
   * @date 2022/1/11 13:46
   */
  protected String getLoginUserRoleCodes() {
    SysUserModel su = this.getLoginUserInfo();
    return su.getRoleCodes();
  }

  /**
   * @param roleCode
   * @return boolean
   * @descript 验证用户是否是某个角色
   * @author lituo
   * @date 2022/1/11 13:48
   */
//  protected boolean checkUserRole(String roleCode) {
//    String roleCodes = this.getLoginUserRoleCodes();
//    boolean matchFlag = false;
//    for(String rc:roleCodes.split(",")){
//      if(StringUtil.isEmpty(rc)){
//        continue;
//      }
//      if(rc.equals(roleCode)){
//        matchFlag = true;
//        break;
//      }
//    }
//    return matchFlag;
//  }



  /**
   * @desc 验证用户是否包含此角色
   * @author lituo
   * @date 2023/4/5 9:32 上午 @param roleCode
   * @return boolean
   */
  protected boolean hasRole(String roleCode){
    String roleCodes = getLoginUserRoleCodes();
    boolean result = false;
    for(String userRoleCode:roleCodes.split(",")){
      if(StringUtil.isEmpty(userRoleCode)){
        continue;
      }
      if(roleCode.equals(userRoleCode)){
        result = true;
        break;
      }
    }
    return result;
  }

  /**
   * 根据登录用户查询组织机构查询范围
   * @param orgId
   * @return
   */
  protected String[] queryCondOrgIds(String orgId){
    if(!StringUtil.isEmpty(orgId)){
      //带入了orgId
      SysOrg sysOrg = new SysOrg();
      sysOrg.setOrgId(orgId);
      SysOrgModel som = sysOrgService.selectByPrimaryKey(sysOrg);
      if(som==null){
        throw new OriginException("组织机构不存在");
      }
      //步骤1、验证是否最底层机构，是则直接查询
      if(som.getOrgLevel()==4){
        String[] orgIds = new String[]{som.getOrgId()};
        return orgIds;
      }
      //步骤2、不是最底层机构，获取下级层级的所有机构，再匹配自身拥有的机构，获取机构列表
      //步骤2.1、获取当前orgId下面所有的子机构
      List<SysOrgModel> subList = sysOrgService.selectListByParOrgId(orgId);
      //步骤2.2、获取当前有权限的子机构
      List<SysUserOrgModel> myList = this.getUserOrgIList();
      //步骤2.3、两个list求合计，且level=4，返回一个新的list
      //获取层次为4的集合
      Set<String> validOrgIds = subList.stream()
              .filter(org -> org.getOrgLevel() == 4)
              .map(SysOrgModel::getOrgId)
              .collect(Collectors.toSet());
      //求合集
      List<SysUserOrgModel> lastList = myList.stream()
              .filter(userOrg -> validOrgIds.contains(userOrg.getOrgId()))
              .collect(Collectors.toList());
      //返回成一个数组
      return lastList.stream()
              .map(SysUserOrgModel::getOrgId)
              .toArray(String[]::new);
    }else{
      //没有带入orgId
      //步骤1、查询所有的机构（只包含最底层）
      List<SysUserOrgModel> list = this.getUserOrgIList();
      String str = "";
      for(int i=0;i<list.size();i++){
        if(list.get(i).getOrgLevel()!=4){
          continue;
        }
        str += list.get(i).getOrgId()+",";
      }
      String[] orgIds =  Arrays.stream(str.split(",", -1)) // 保留所有分割项（包括末尾空元素）
              .filter(s -> !s.trim().isEmpty()) // 过滤空字符串和纯空格
              .toArray(String[]::new);
      return orgIds;
    }
  }
}
